﻿#include "Framework/Application.h"
#include "Object/NewObject.h"
#include "Misc/CommandLineArgumentsParser.h"
#include "ScriptRuntime/ScriptSubsystem.h"
#include "Output/Console.h"

#include "Path/Paths.h"
#include "File/FileUtils.h"

#include "ScriptCompiler/Compiler.h"

int main(int argc, char* argv[])
{
    auto App=NewObject<RApplication>();
    SApplicationArgument Arguments;
    Arguments.ExecutablePath=SPath(argv[0]);
    Arguments.WorkThreadNum=4;
    
    App->Initialize(Arguments);


    CCommandLineArgumentsParser Parser;
    {
        SPath ProjectPath;
        Parser.AddOption(U"ProjectDir",U"项目所在的目录",ProjectPath);
    }
    {
        SPath TargetFolder;
        Parser.AddOption(U"OutputDir",U"打包后存放的文件夹",TargetFolder);
    }
    {
        CString ProjectName;
        Parser.AddOption(U"ProjectName",U"项目名称",ProjectName);
    }
    {
        CString Platform; //Win64 or Linux
        Parser.AddOption(U"Platform",U"平台",Platform);
    }

    auto Error=Parser.Parse(argc,argv);
    if(Error.HasValue())
    {
        WH::PrintLine(U"参数错误: ");
        WH::PrintLine(Error.GetValue());
        return 1;
    }



    SPath ProjectPath;
    assert(Parser.IsOptionSet(U"ProjectDir"));
    ProjectPath=Parser.GetValue<SPath>(U"ProjectDir");
    

    SPath TargetFolder;
    assert(Parser.IsOptionSet(U"OutputDir"));
    TargetFolder=Parser.GetValue<SPath>(U"OutputDir");
    
    CString ProjectName;
    assert(Parser.IsOptionSet(U"ProjectName"));
    ProjectName=Parser.GetValue<CString>(U"ProjectName");

    CString Platform;
    assert(Parser.IsOptionSet(U"Platform"));
    Platform=Parser.GetValue<CString>(U"Platform");

    WH::PrintLine(U"开始打包项目: "+ProjectName);

    //1.编译脚本
    auto CompileError= WH::CompileProjectScripts(ProjectPath);
    if(CompileError.HasValue())
    {
        WH::PrintLine(U"编译失败");
        WH::PrintLine(CompileError.GetValue());
        return 1;
    }
    else
    {
        WH::PrintLine(U"编译成功");
    }

    //2.将ScriptProjectTemplate复制到输出目录并重命名为ProjectName
    SPath ScriptProjectRunnerFolder= SPaths::GetExecutablePath().Parent()/U"ProjectTemplate/"/Platform;
    assert(ScriptProjectRunnerFolder.IsDirectory() && ScriptProjectRunnerFolder.Exists());

    CString ScriptProjectRunnerExeName=Platform==U"Win64"?U"ScriptProjectTemplate.exe":U"ScriptProjectTemplate";
    CString NewExeName=Platform==U"Win64"?ProjectName+U".exe":ProjectName;

    SFileUtils::CopyDirectory(ScriptProjectRunnerFolder,TargetFolder);
    SFileUtils::RenameFileOrDirectory(TargetFolder/ScriptProjectRunnerExeName,NewExeName);

    //3.将Project复制到输出目录
    SFileUtils::CopyDirectory(ProjectPath,TargetFolder/U"Project");


    return 0;
}